package com.example.exercise.common.exception;

import com.example.exercise.common.base.BaseResponse;
import io.swagger.v3.oas.annotations.Hidden;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一的异常处理
 */
@Hidden
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class) // 全局捕获异常
    @ResponseBody
    public BaseResponse<Object> handleGlobalException(Exception e) {
        BaseResponse<Object> baseResponse = new BaseResponse<>();
        if(e instanceof BusinessException){
            baseResponse.setCode(-2147);
            baseResponse.setMsg("自定义错误信息：" + e.getMessage());
        }else{
            baseResponse.setCode(-2148);
            baseResponse.setMsg("系统错误信息：" + e.getMessage());
        }
        LOGGER.error(e.getMessage(), e);
        return baseResponse;
    }

}
